package run

import (
	"context"
	"log"
	"time"

	"gitee.com/go-errors/errors"
)

func Delay(ctx context.Context, do func(), delay time.Duration) context.CancelFunc {
	delayCtx, cancel := context.WithTimeout(context.Background(), delay)
	go func() {
		select {
		case <-ctx.Done():
			cancel()
		case <-delayCtx.Done():
			switch delayCtx.Err() {
			case context.DeadlineExceeded:
				do()
			case context.Canceled:
			}
		}
	}()
	return cancel
}

func Proper(ctx context.Context, functions ...ProperFunc) error {
	for _, function := range functions {
		if err := function(ctx); err != nil {
			return errors.Wrap(err)
		}
	}
	return nil
}

func Run(ctx context.Context, fn ProperFunc) {
	if err := fn(ctx); err != nil {
		log.Printf("%v", err)
	}
}

type ProperFunc func(context.Context) error

func (fn ProperFunc) WithTime(d *time.Duration) ProperFunc {
	return func(ctx context.Context) error {
		defer func(start time.Time) { *d = time.Since(start) }(time.Now())
		return fn(ctx)
	}
}

func WithTime(fn ProperFunc, d *time.Duration) ProperFunc {
	return fn.WithTime(d)
}
